package com.xin.chaingeneration.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xin.chaingeneration.common.ResponseEntity;
import com.xin.chaingeneration.entity.Product;
import com.xin.chaingeneration.entity.ProductDto;
import com.xin.chaingeneration.entity.ProductType;
import com.xin.chaingeneration.service.ProductService;
import com.xin.chaingeneration.service.ProductTypeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    ProductService productService;

    @Autowired
    ProductTypeService productTypeService;

    @PostMapping("/addProduct")
    public ResponseEntity<Product> addProduct(@RequestBody ProductDto productDto){

        log.info(productDto.toString());

        String dtoTypeName = productDto.getProductType();

        boolean exist = productTypeService.existsByTypeName(dtoTypeName);

        Product product = new Product();


        if (!exist){
            ProductType productType = new ProductType();
            productType.setTypeName(dtoTypeName);
            productTypeService.saveOrUpdate(productType);

            product.setUserId(productDto.getUserId());
            product.setProductName(productDto.getProductName());
            product.setTypeId(productType.getId());
            productService.saveOrUpdate(product);
        }else{
            LambdaQueryWrapper<ProductType> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ProductType::getTypeName,productDto.getProductType());
            ProductType one = productTypeService.getOne(queryWrapper);


            product.setUserId(productDto.getUserId());
            product.setProductName(productDto.getProductName());
            product.setTypeId(one.getId());
            productService.saveOrUpdate(product);
        }

        ResponseEntity<Product> productResponseEntity = new ResponseEntity<>();
        productResponseEntity.setData(product);
        productResponseEntity.setCode(1);

        return productResponseEntity;
    }
}
